package com.swim.phonenumprivacy.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 *   字符串存储工具类
 * @author ljw
 */
public class StringStorageUtil {
	
    private final Map<String, Long> dataMap = new HashMap<>();  
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);  
    
    /**
          * 存储字符串
     * @param str
     */
    public void storeData(String str) {  
        long currentTimeMillis = System.currentTimeMillis();  
        dataMap.put(str, currentTimeMillis); // 存储数据ID和当前时间戳  
        scheduler.schedule(() -> {  
            long storedTime = dataMap.get(str);  
            if (System.currentTimeMillis() - storedTime > 5 * 60 * 1000) {  
                dataMap.remove(str); // 数据存储超过5分钟，移除数据和时间戳  
            }  
        }, 5, TimeUnit.MINUTES); // 5分钟后检查  
    }  
    
    /**
           * 获取存储超过5分钟的数据
     * @return List<String>
     */
    public List<String> getExpiredIds() {  
        List<String> expiredIds = new ArrayList<>();  
        for (Map.Entry<String, Long> entry : dataMap.entrySet()) {  
            if (System.currentTimeMillis() - entry.getValue() > 5 * 60 * 1000) {  
                expiredIds.add(entry.getKey()); // 返回过期数据的ID  
            }  
        }  
        return expiredIds;  
    }    
}
